/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GrupoDialog.java
 *
 * Created on 20/10/2011, 23:14:56
 */
package br.com.seguradora.view.dialog;

import br.com.seguradora.exception.InputValidationException;
import br.com.seguradora.exception.PersistenciaException;
import br.com.seguradora.model.Marca;
import br.com.seguradora.model.Modelo;
import br.com.seguradora.service.MarcaService;
import br.com.seguradora.service.ModeloService;
import br.com.seguradora.view.ErrorsList;
import br.com.seguradora.view.UserError;
import br.com.seguradora.view.StateEntityWindow;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.Iterator;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;

/**
 *
 * @author Diego
 */
public class ModeloDialog extends javax.swing.JDialog {
    
    private Modelo modelo;
    private final static String titleWindow = "Modelo";
    private StateEntityWindow stateEntity;
    
    public ModeloDialog(java.awt.Frame parent, boolean modal, StateEntityWindow stateEntity, Modelo modelo) {
        super(parent, modal);
        initComponents();
        this.stateEntity = stateEntity;
        setTitle(titleWindow + stateEntity);
        organizeWindow();
        setModelo(modelo);
        setLocationRelativeTo(null);
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cabecalhoPanel = new br.com.seguradora.view.panel.CabecalhoPanel();
        jLabel1 = new javax.swing.JLabel();
        nomeField = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        confirmarButton = new javax.swing.JButton();
        cancelarButton = new javax.swing.JButton();
        nomeErrorLabel = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        marcaCombo = new javax.swing.JComboBox();
        marcaErrorLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Nome:");

        confirmarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/accept.png"))); // NOI18N
        confirmarButton.setText("Confirmar");
        confirmarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                confirmarButtonActionPerformed(evt);
            }
        });

        cancelarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/cross.png"))); // NOI18N
        cancelarButton.setText("Cancelar");
        cancelarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarButtonActionPerformed(evt);
            }
        });

        nomeErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/exclamation.png"))); // NOI18N

        jLabel2.setText("Marca:");

        marcaErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/exclamation.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(cabecalhoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(72, 72, 72)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(marcaCombo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(nomeField, javax.swing.GroupLayout.DEFAULT_SIZE, 226, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(marcaErrorLabel)
                            .addComponent(nomeErrorLabel))))
                .addContainerGap(22, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(122, Short.MAX_VALUE)
                .addComponent(confirmarButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancelarButton)
                .addGap(78, 78, 78))
            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(cabecalhoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(marcaCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(marcaErrorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nomeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(nomeErrorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(confirmarButton)
                    .addComponent(cancelarButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        dispose();
    }//GEN-LAST:event_cancelarButtonActionPerformed
    
    private void confirmarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_confirmarButtonActionPerformed
        try {
            validateUserInput();
            ModeloService modeloService = new ModeloService();
            Modelo modelo = getModelo();
            if (getStateEntity() == StateEntityWindow.NEW) {
                modeloService.inserir(modelo);
            } else if (getStateEntity() == StateEntityWindow.UPDATE) {
                modeloService.atualizar(modelo);
            }
            dispose();
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        } catch (InputValidationException ivex) {
            JOptionPane.showMessageDialog(null, "Erros foram encontrados.", "Mensagem do sistema", JOptionPane.ERROR_MESSAGE);
            ErrorsList errorsList = ivex.getErrorsList();
            for (Iterator<UserError> it = errorsList.iterator(); it.hasNext();) {
                UserError userError = it.next();
                showErrorLabel(userError);
            }
        }
    }//GEN-LAST:event_confirmarButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            System.out.println(ex);
        }
        //</editor-fold>
        java.awt.EventQueue.invokeLater(new Runnable() {
            
            public void run() {
                ModeloDialog dialog = new ModeloDialog(new javax.swing.JFrame(), true, StateEntityWindow.NEW, null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private br.com.seguradora.view.panel.CabecalhoPanel cabecalhoPanel;
    private javax.swing.JButton cancelarButton;
    private javax.swing.JButton confirmarButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JComboBox marcaCombo;
    private javax.swing.JLabel marcaErrorLabel;
    private javax.swing.JLabel nomeErrorLabel;
    private javax.swing.JTextField nomeField;
    // End of variables declaration//GEN-END:variables

    private void setModelo(Modelo modelo) {
        if (modelo == null) {
            return;
        }
        this.modelo = modelo;
        cabecalhoPanel.setCodigo(modelo.getId());
        cabecalhoPanel.setBloqueado(modelo.isBloqueado());
        nomeField.setText(modelo.getNome());
        marcaCombo.setSelectedItem(modelo.getMarca());
    }
    
    private Modelo getModelo() {
        if (modelo == null) {
            modelo = new Modelo();
        }
        modelo.setBloqueado(cabecalhoPanel.isBloqueado());
        modelo.setNome(nomeField.getText().toUpperCase());
        modelo.setMarca((Marca) marcaCombo.getSelectedItem());
        return modelo;
    }
    
    private void organizeWindow() {
        marcasToCombo();
        if (getStateEntity() == StateEntityWindow.NEW) {
            cabecalhoPanel.isEnabledComponentBloqueado(false);
        }
        isShowErrorsLabel(false);
    }
    
    public StateEntityWindow getStateEntity() {
        return stateEntity;
    }
    
    private void validateUserInput() throws InputValidationException {
        isShowErrorsLabel(false);
        ErrorsList errorsList = new ErrorsList();
        if (nomeField.getText().isEmpty()) {
            errorsList.addError(new UserError(nomeErrorLabel, "O nome do modelo não foi informado."));
        }        
        if (marcaCombo.getSelectedItem() == null) {
            errorsList.addError(new UserError(marcaErrorLabel, "A marca do modelo não foi informada."));            
        }        
        if (errorsList.countErrors() > 0) {
            throw new InputValidationException(errorsList);
        }
    }
    
    private void isShowErrorsLabel(boolean show) {
        nomeErrorLabel.setVisible(show);
        marcaErrorLabel.setVisible(show);
    }
    
    private void showErrorLabel(UserError userError) {
        userError.getLabel().setVisible(true);
    }
    
    private void marcasToCombo() {
        try {
            MarcaService marcaService = new MarcaService();
            DefaultComboBoxModel model = new DefaultComboBoxModel(marcaService.listarTodos().toArray());
            marcaCombo.setModel(model);
            marcaCombo.setSelectedItem(null);
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
    }
    
    public Modelo objetoModelo() {
        return modelo;
    }
    
    @Override
    protected JRootPane createRootPane() {
        ActionListener closeListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                cancelarButtonActionPerformed(e);
            }
        };
        KeyStroke stroke =
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        JRootPane myRootPane = new JRootPane();
        myRootPane.registerKeyboardAction(
                closeListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        return myRootPane;
    }
}
